package com.tju.backend.resources.controller.attest;

import com.tju.backend.entity.SysUser;
import com.tju.backend.utils.result.*;
import com.tju.backend.utils.tool.ChineseExceptionUtils;
import com.tju.backend.utils.tool.ClientParameters;
import com.tju.backend.service.business.SysUserService;
import com.tju.backend.service.common.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;
import java.util.Optional;

/**
 * @USER: CLS
 */
@RestController
public class SysUserController {
    private final String prefix = "user";

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ChineseExceptionUtils zh_CN;

    /**
     * 分页查询用户管理
     *
     * @param parameters
     * @return
     */
    @PostMapping(prefix + "/selUser.do")
    public Result<Object> selUser(@RequestBody ClientParameters parameters) {
        return Optional.ofNullable(parameters.getRole())
                .map(p -> sysUserService.selUser(parameters))
                .orElseThrow(() -> new ServiceException(zh_CN.UnknownException));
    }

    /**
     * 新增用户
     *
     * @param sysUser
     * @return
     */
    @PostMapping(prefix + "/addUser.do")
    public Result<Object> addUser(@Valid @RequestBody SysUser sysUser, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else
            return sysUserService.addUser(sysUser);
    }

    /**
     * 修改用户
     *
     * @param sysUser
     * @return
     */
    @PostMapping(prefix + "/updateUser.do")
    public Object updateUser(@Valid @RequestBody SysUser sysUser, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else
            return Optional.ofNullable(sysUser.getId())
                    .map(u -> sysUserService.updateUser(sysUser))
                    .orElseThrow(() -> new ServiceException(zh_CN.IdAnomaly));
    }

    /**
     * 删除用户
     *
     * @param sysUser
     * @return
     */
    @PostMapping(prefix + "/delUser.do")
    public Result<Object> delUser(@RequestBody SysUser sysUser) {
        return sysUserService.delUser(sysUser);
    }

}
